import { Directive, ElementRef, Input, OnInit, OnDestroy, Renderer2, AfterViewInit } from '@angular/core';
//Controls
import { AmChartsService } from "@amcharts/amcharts3-angular";

/**
 * TODO: reduce param numbers and take into consideration multiple guides
 */
@Directive({
    selector: '[scatterChart]',
})
export class ScatterChartDirective implements OnInit, OnDestroy {
    private chart: any;
    private _chartData: any[] = [];
    private _peersList: any[];
    //private _legendData: any[] = [];

    @Input() chartID: string;
    //if true, the chart defined 3 assessment levels for each axis (Low, Medium, High). Max level of 10 is required
    @Input() assessmentAxis: boolean;
    //if true, display the description nside each bullet
    @Input() bulletLabel: boolean;

    @Input() verticalAxisName: string;
    @Input() verticalAxisMax;

    @Input() horizontalAxisName: string;
    @Input() horizontalAxisMax;
    @Input() horizontalAxisHeight: number = 100;
    @Input() dateAxis: boolean = false;
    @Input() startDate: string;
    @Input() revertVertical: boolean = true;

    @Input() set riskLevels(value: any[]) {
        /* if (value) {
            // this._legendData = this.generateLegend(value);
            if (this.chart) {
                this.AmCharts.updateChart(this.chart, () => {
                    // this.chart.legend.data = this._legendData;
                });
            }
        } */
    }

    @Input() currentColor = '#000000';
    @Input() currentSize = 12;
    @Input() currentAlpha = 1;
    @Input() otherColor = '#175F96';
    @Input() universeColor = 'lightgray';
    @Input() lineColor = '#ffa500';
    @Input() universeSize = 4;
    @Input() otherSize = 8;
    @Input() otherAlpha = 1;
    @Input() axisAlpha = 0;
    @Input() gridAlpha = 0;
    @Input() subIndustryAverageExposure: number;
    @Input() subIndustryAverageManagement: number;

    @Input() set chartData(value: any[]) {
        if (value) {
            this._chartData = value;
            if (this.chart) {
                this.AmCharts.updateChart(this.chart, () => {
                    this.chart.dataProvider = this._chartData;
                });
            }
        }
    }
    @Input() set peersList(value: any[]) {
        if (value) {
            this._peersList = value;
        }
    }

    constructor(private el: ElementRef, private AmCharts: AmChartsService, private renderer: Renderer2) { }

    ngOnInit() {
        let baloonFunc = function (graphDataItem, graph) {
            return  (graphDataItem.dataContext.name ? graphDataItem.dataContext.name + "<br/>" : '') + (graph.xAxis.title ? (graph.xAxis.title + ": <b>" + graphDataItem.values.x.toFixed(1) + "</b><br/>") : '') + graph.yAxis.title + ": <b>" + graphDataItem.values.y.toFixed(1) + "</b>";        
        }

        const self = this;
        let horizontalAxis = {
            id: "horizontal",
            position: "bottom",
            title: this.horizontalAxisName,
            minimum: 0,
            maximum:  this.horizontalAxisMax,
            gridCount: 10,
            autoGridCount: false,
            gridAlpha: this.assessmentAxis ? this.gridAlpha : 1,
            axisAlpha: this.axisAlpha,
            gridThickness: this.assessmentAxis ? 0.2 : 0,
            dashLength: 0,
            labelsEnabled: !this.assessmentAxis,
            labelFunction: function(valueText) {
                if (valueText === 0 ) {
                    return 'Low';
                } else if (valueText === self.horizontalAxisMax) {
                    return 'High';
                }

                return '';
            },
            tickLength: 0,
            reversed: false
        };

            //if required, make this dynamic data
        let guides = [
            {
                id: "Guide-1",
                label: "Low",
                lineAlpha: 1,
                toValue: 0,
                value: 3.33,
                valueAxis: "horizontal"
            },
            {
                id: "Guide-2",
                label: "Medium",
                lineAlpha: 1,
                toValue: 3.33,
                value: 6.66,
                valueAxis: "horizontal"
            },
            {
                id: "Guide-3",
                label: "High",
                lineAlpha: 1,
                toValue: 6.66,
                value: 10,
                valueAxis: "horizontal"
            },
            {
                id: "Guide-4",
                label: "Low",
                lineAlpha: 1,
                toValue: 0,
                value: 3.33,
                valueAxis: "vertical"
            },
            {
                id: "Guide-5",
                label: "Medium",
                lineAlpha: 1,
                toValue: 3.33,
                value: 6.66,
                valueAxis: "vertical"
            },
            {
                id: "Guide-6",
                label: "High",
                lineAlpha: 1,
                toValue: 6.66,
                value: 10,
                valueAxis: "vertical"
            },
            {
                'fillAlpha': this.axisAlpha,
                'value': 10,
                'toValue': 10
            }
        ];
        this.chart = this.AmCharts.makeChart(this.chartID, {
            type: "xy",
            startDuration: 0,
            marginTop: 30,
            pathToImages: './assets/img/',
          
            graphs: [
                //universe
                {
                    bullet: "round",
                    bulletSize: this.universeSize,
                    bulletAlpha: this.otherAlpha,
                    lineAlpha: 0,
                    bulletColor: this.universeColor,
                    name: "name",
                    xField: "peerX",
                    yField: "peerY",
                    labelText:  this.bulletLabel ? '[[description]]' : '',
                    labelPosition: "middle",
                    balloonFunction: baloonFunc
                },
                //SubIndustry
                {
                    bullet: "round",
                    bulletSize: this.otherSize,
                    bulletAlpha: this.otherAlpha,
                    lineAlpha: 0,
                    bulletColor: this.otherColor,
                    name: "name",
                    xField: "X",
                    yField: "Y",
                    labelText:  this.bulletLabel ? '[[description]]' : '',
                    labelPosition: "middle",
                    balloonFunction: baloonFunc
                },
                //current
                {
                    bullet: "round",
                    bulletSize: this.currentSize,
                    bulletAlpha: this.currentAlpha,
                    lineAlpha: 0,
                    fontSize: 8,
                    bulletColor: this.currentColor,
                    color: "white",
                    balloonFunction: baloonFunc,
                    xField: "currentX",
                    yField: "currentY",
                    descriptionField: "peerPosition",
                    labelText:  this.bulletLabel ? '[[description]]' : '',
                    labelPosition: "middle"
                }
            ],
      
            allLabels: this.assessmentAxis ? [] : [{
                'x': '!35',
                'y': '35',
                'text': 'Severe Risk',
                'align': 'right',
                'size': 10
                }, {
                'x': '85',
                'y': '!75',
                'text': 'Negligible Risk',
                'align': 'left',
                'size': 10
                }],
            guides: this.assessmentAxis ? guides : [
                {
                    'fillAlpha': this.axisAlpha,
                    'value':  this.verticalAxisMax,
                    'toValue': this.verticalAxisMax
                },
                {
                    'fillAlpha': this.axisAlpha,
                    'value': this.horizontalAxisMax,
                    'toValue': this.horizontalAxisMax,
                    'valueAxis': 'horizontal'
                },
                {
                    'fillAlpha': this.axisAlpha,
                    'value':  0,
                    'toValue': 0,
                }
            ],
            valueAxes: [
                {
                    id: "vertical",
                    minimum: 0,
                    maximum: this.verticalAxisMax,
                    title: this.verticalAxisName,
                    axisAlpha: this.axisAlpha,
                    gridAlpha: this.gridAlpha,
                    dashLength: 0,
                    autoGridCount: false,
                    gridCount: 10,
                    gridThickness: 0.2,
                    labelsEnabled: !this.assessmentAxis,
                    labelFunction: function(valueText) {
                        if (valueText === 0) {
                            return 'Weak';
                        } else if (valueText === self.verticalAxisMax) {
                            return 'Strong';
                        }

                        return '';
                    },
                    tickLength: 0,
                    reversed: this.revertVertical
                },
                horizontalAxis
            ],
            trendLines: [
                {
                    "initialValue": 0,
                    "initialXValue": this.subIndustryAverageExposure,
                    "finalValue": 100,
                    "finalXValue": this.subIndustryAverageExposure,
                    "lineColor": this.lineColor,
                    "dashLength":3,
                    "balloonText":(this.subIndustryAverageExposure>0)?"SubIndustry Average Exposure:"+this.subIndustryAverageExposure.toFixed(2):""
                },
                {
                    "initialValue": this.subIndustryAverageManagement,
                    "initialXValue": 0,
                    "finalValue": this.subIndustryAverageManagement,
                    "finalXValue": 100,
                    "lineColor": this.lineColor,
                    "dashLength":3,
                    "balloonText":(this.subIndustryAverageManagement>0)?"SubIndustry Average Management:"+this.subIndustryAverageManagement.toFixed(2):""
                }
                
            ],
            minValue: -10,
            dataProvider: this._chartData,
             listeners: [
                {
                    event: 'rendered',
                    method: function(e){
                        e.chart.graphsSet.toBack();
                        e.chart.trendLinesSet.toFront();
                    }
                }
            ]  
           
        });
    }

    ngOnDestroy() {
        this.AmCharts.destroyChart(this.chart);
    }
}